package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private WorkspaceService workspaceService;


    /**
     * 根据时间区间统计营业额
     *
     * @param begin 起始日期
     * @param end   结束日期
     * @return 返回营业额报告的VO对象
     */
    public TurnoverReportVO getTurnover(LocalDate begin, LocalDate end) {
        // 初始化日期列表，用于存放起始日期到结束日期之间的所有日期
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);

        // 循环直到起始日期等于结束日期，每次循环将起始日期加1天
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        // 初始化营业额列表，用于存放每个日期对应的营业额
        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate date : dateList) {
            // 根据日期计算当日开始和结束时间
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);// 00:00:00
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);// 23:59:59

            // 创建查询条件Map
            //为什么创建map对象，因为map对象可以存放多个键值对，而map对象可以作为参数传递给方法，所以可以传递多个参数
            Map map = new HashMap();
            map.put("status", Orders.COMPLETED);
            map.put("begin", beginTime);
            map.put("end", endTime);

            // 调用Mapper查询当日营业额总和
            Double turnover = orderMapper.sumByMap(map);

            // 对查询结果进行空值处理，避免null值
            turnover = turnover == null ? 0.0 : turnover;

            turnoverList.add(turnover);
        }

        // 使用Builder模式构建并返回营业额报告的VO对象
        return TurnoverReportVO.builder()
                //通过调用org.apache.commons.lang3包下的StringUtils的join方法将dateList转换为逗号分隔的字符串
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
    }

    @Override
    public UserReportVO getUser(LocalDate begin, LocalDate end) {
        // 初始化日期列表，用于存放起始日期到结束日期之间的所有日期
        List<LocalDate> dateList = new ArrayList<>();
        // 循环直到起始日期等于结束日期，每次循环将起始日期加1天
        dateList.add(begin);

        // 初始化用户列表，用于存放每个日期对应的用户数量
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        // 初始化用户列表，用于存放每个日期对应的用户数量
        List<Integer> newUserList = new ArrayList<>();//新增用户列表
        List<Integer> totalUserList = new ArrayList<>();//用户总数列表

        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);// 00:00:00
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);// 23:59:59

            // 创建查询条件Map
            Map map = new HashMap();
            map.put("begin", beginTime);
            map.put("end", endTime);

            // 调用Mapper查询当日用户总和
            Integer totalUser = userMapper.usertotalByMap(map);
            totalUser = totalUser == null ? 0 : totalUser;

            Integer newUser = userMapper.newUserByMap(map);
            newUser = newUser == null ? 0 : newUser;

            newUserList.add(newUser);
            totalUserList.add(totalUser);
        }
        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .build();
    }

    /**
     * 获取订单数据统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO getOrder(LocalDate begin, LocalDate end) {
        // 初始化日期列表，用于存放起始日期到结束日期之间的所有日期
        List<LocalDate> dateList = new ArrayList<>();
        // 循环直到起始日期等于结束日期，每次循环将起始日期加1天
        dateList.add(begin);

        // 初始化用户列表，用于存放每个日期对应的用户数量
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        List<Integer> orderCountList = new ArrayList<>();
        List<Integer> validOrderCountList = new ArrayList<>();

        Integer totalOrderCount = 0;//订单总数
        Integer validOrderCount = 0;//有效订单数量

        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);// 00:00:00
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);// 23:59:59

            // 创建查询条件Map
            Map map = new HashMap();
            map.put("begin", beginTime);
            map.put("end", endTime);

            // 调用Mapper查询当天的订单总数
            Integer orderCountday = orderMapper.OrderCountByMap(map);
            totalOrderCount = totalOrderCount + orderCountday;//订单总数

            map.put("status", Orders.COMPLETED);
            // 调用Mapper查询当天的有效订单总数
            Integer validOrderCountday = orderMapper.OrderCountByMap(map);
            validOrderCount = validOrderCount + validOrderCountday;

            // 计算订单总数
            orderCountList.add(orderCountday);
            // 计算有效订单数量
            validOrderCountList.add(validOrderCountday);
        }

        //订单完成率
        Double orderCompletionRate = 0.0;
        if (totalOrderCount != 0) {
            orderCompletionRate = (double) validOrderCount / totalOrderCount;
        }

        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCompletionRate(orderCompletionRate)
                .orderCountList(StringUtils.join(orderCountList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .build();
    }

    /**
     * 查询指定时间区间内的销量排名top10
     * @param begin 起始日期
     * @param end 结束日期
     * @return 销量排名top10的报告对象
     */
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end){
        // 根据传入的日期范围，设置查询的开始和结束时间
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        // 通过orderMapper查询指定时间区间内销量排名前10的商品
        List<GoodsSalesDTO> goodsSalesDTOList = orderMapper.getSalesTop10(beginTime, endTime);

        // 使用StringBuilder来拼接商品名称和数量的字符串，用于后续构建报告对象
        StringBuilder nameListBuilder = new StringBuilder();
        StringBuilder numberListBuilder = new StringBuilder();

        // 标记是否是第一次处理，用于处理字符串拼接时的分隔符问题
        boolean isFirst = true;
        // 遍历商品销售数据列表，拼接商品名称和数量字符串
        for (GoodsSalesDTO goods : goodsSalesDTOList) {
            // 如果不是第一次处理，则在商品名称和数量字符串中添加分隔符
            if (!isFirst) {
                nameListBuilder.append(",");
                numberListBuilder.append(",");
            } else {
                // 标记已经处理过至少一个商品
                isFirst = false;
            }

            // 拼接商品名称和数量到对应的StringBuilder对象中
            nameListBuilder.append(goods.getName());
            numberListBuilder.append(goods.getNumber());
        }

        // 将拼接好的商品名称和数量字符串转换为最终的报告对象属性
        String nameList = nameListBuilder.toString();
        String numberList = numberListBuilder.toString();

        // 构建并返回销量排名top10的报告对象
        return SalesTop10ReportVO.builder()
                .nameList(nameList)
                .numberList(numberList)
                .build();
    }


    /**导出近30天的运营数据报表
     * @param response HTTP响应对象，用于将生成的报表文件输出到客户端
     **/
    public void exportBusinessData(HttpServletResponse response) {
        //计算开始日期和结束日期，分别指向30天前和昨天
        LocalDate begin = LocalDate.now().minusDays(30);
        LocalDate end = LocalDate.now().minusDays(1);
        //查询概览运营数据，提供给Excel模板文件
        BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(begin,LocalTime.MIN), LocalDateTime.of(end, LocalTime.MAX));
        //加载模板文件
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            //基于提供好的模板文件创建一个新的Excel表格对象
            XSSFWorkbook excel = new XSSFWorkbook(inputStream);
            //获得Excel文件中的一个Sheet页
            XSSFSheet sheet = excel.getSheet("Sheet1");

            //设置报表日期范围
            sheet.getRow(1).getCell(1).setCellValue(begin + "至" + end);



            //获得第4行
            XSSFRow row = sheet.getRow(3);
            //获取单元格并设置概览数据
            row.getCell(2).setCellValue(businessData.getTurnover());
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessData.getNewUsers());
            //设置其他概览数据
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessData.getValidOrderCount());
            row.getCell(4).setCellValue(businessData.getUnitPrice());




            //循环填充每日明细数据
            for (int i = 0; i < 30; i++) {
                LocalDate date = begin.plusDays(i);
                //准备明细数据
                businessData = workspaceService.getBusinessData(LocalDateTime.of(date,LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
                row = sheet.getRow(7 + i);
                //设置日期
                row.getCell(1).setCellValue(date.toString());
                //设置营业额
                row.getCell(2).setCellValue(businessData.getTurnover());
                //设置有效订单量
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                //设置订单完成率
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                //设置客单价
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                //设置新增用户数
                row.getCell(6).setCellValue(businessData.getNewUsers());
            }




            //通过输出流将文件下载到客户端浏览器中
            ServletOutputStream out = response.getOutputStream();
            //写入Excel数据到输出流
            excel.write(out);
            //关闭资源
            out.flush();
            out.close();
            excel.close();

        }catch (IOException e){
            //处理异常
            e.printStackTrace();
        }
    }


}
